package com.example.myanimator.mcanvas

import android.content.Context
import android.graphics.*
import android.graphics.drawable.ShapeDrawable
import android.graphics.drawable.shapes.OvalShape
import android.graphics.drawable.shapes.RectShape
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.core.graphics.drawable.toBitmap
import com.example.myanimator.R

/**
 * @author tgw
 * @date 2021/4/6
 * @describe  放大镜效果
 */
class TelescropeView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    var mShapeDrawable: ShapeDrawable? = null
    var mBitmap: Bitmap? = null

    //放大倍数
    val FACTOR: Int = 3

    //放大镜半径
    val RADIUS: Int = 80

    private lateinit var mMatrix: Matrix

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        if (mBitmap == null) {
            var bitmap = BitmapFactory.decodeResource(resources, R.mipmap.aa)
            mBitmap = Bitmap.createScaledBitmap(bitmap, width, height, false)
            //创建一个放大三倍的bitmap
            var scaleBitmap = Bitmap.createScaledBitmap(mBitmap!!, mBitmap!!.width * FACTOR, mBitmap!!.height * FACTOR, true)
            var shader = BitmapShader(scaleBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
            mShapeDrawable = ShapeDrawable(OvalShape())
            mShapeDrawable?.let {
                it.paint.shader = shader
                it.setBounds(0,0,RADIUS*2,RADIUS*2)
            }
        }
        canvas?.let {//画出原图像
            it.drawBitmap(mBitmap!!,0f,0f,null)
        }

        //画出shader图像
        mShapeDrawable?.draw(canvas!!)


    }

    init {
        setLayerType(LAYER_TYPE_SOFTWARE, null) //禁用加速
        mMatrix = Matrix()
    }


    override fun onTouchEvent(event: MotionEvent?): Boolean {
        var x:Int = event!!.x.toInt()
        var y:Int = event!!.y.toInt()
        //这里表示的是绘制shader的起始位置
        mMatrix.setTranslate((RADIUS-x*FACTOR).toFloat(), (RADIUS-y*FACTOR).toFloat()) //移动画布使点击的地方就是画布的地方
        mShapeDrawable?.let {
            it.paint.shader.setLocalMatrix(mMatrix)
            it.setBounds(x-RADIUS,y-RADIUS,x+RADIUS,y+RADIUS)
        }
        invalidate()
        return true
    }
}